package main

import "C"
import (
	"encoding/base64"
	"fmt"
	"github.com/shirou/gopsutil/host"
	"io/ioutil"
	"os"
	"unsafe"
)

var (
	crtFileUrl = "enc.crt"
	password   = []byte("7ebfbf70f49212ba")
	crtKey     = []byte("zcwtwdnzchqweabc")
)

//export Enc
func Enc(p *C.char, size C.int) *C.char {
	s := C.GoBytes(unsafe.Pointer(p), size)
	body := string(s)

	fmt.Println(body)
	if verify() {
		encrypt := Encrypt([]byte(body), password)
		return C.CString(encrypt)
	}
	return C.CString("")
}

//export Dec
func Dec(p *C.char, size C.int) *C.char {
	s := C.GoBytes(unsafe.Pointer(p), size)
	body := string(s)

	fmt.Println(body)
	if verify() {
		decodeString, err := base64.StdEncoding.DecodeString(body)
		if err != nil {
			return C.CString("")
		}
		decrypt := Decrypt(decodeString, password)
		return C.CString(decrypt)
	}
	return C.CString("")
}

//verify status
var firstInit = true

//GFfZSqQYEOzDWmpMMlsC0vFChlgDHn0VY/Kuyo5wTd1sJpTPBN2nt/cyZf90O3QqBsxv/t6Ow6+o3tkSpfjGBQ==
var initStr = "aoihuweopwieruwejorwerwelrwermwenvabvsspoeiwrerqwerqwpeoitjgwe"

func verify() bool {
	file, err := ioutil.ReadFile(crtFileUrl)
	if err != nil {
		fmt.Println(err)
		return false
	}

	str := string(file)

	if str == "" {
		fmt.Println(err)
		return false
	}

	decodeString, err := base64.StdEncoding.DecodeString(str)
	if err != nil {
		fmt.Println(err)
		return false
	}

	decrypt := Decrypt(decodeString, crtKey)
	id, err := host.HostID()
	if err != nil {
		fmt.Println(err)
		return false
	}
	if decrypt == initStr {
		encrypt := Encrypt([]byte(id), crtKey)
		ioutil.WriteFile(crtFileUrl, []byte(string(encrypt)), os.ModeAppend)
		return true
	} else if decrypt == id {
		return true
	}

	return false
}

func main() {
	//decodeString, _ := base64.StdEncoding.DecodeString("BX1/yGZCpBZF9AKSHLnCe/EzkwK94YO6tPP2axs8XHs0b28jDwmGpBd22zv+tPih")
	//fmt.Println(decodeString)
	//decrypt := Decrypt(decodeString, crtKey)
	//
	//fmt.Println(decrypt)
	//id, _ := host.HostID()
	//fmt.Println(id)
	//b := verify()
	//fmt.Println(b)
}
